package cn.elaixin.poidemo.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *   MD5 工具类
 *   用于获取字符串 String 的 md5 值
 * Created by caoshi at 21:09 2021/4/19
 */
public class MD5Util {

    private static MessageDigest md5 = null;

    static {
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     *  获取 Md5 字符串
     * @param str
     * @return
     */
    public static String getMd5(String str) {
        if (str != null) {
            byte[] bs = md5.digest(str.getBytes());
            StringBuilder sb = new StringBuilder(40);
            for (byte b : bs) {
                if ((b & 0xff) >> 4 == 0) {
                    sb.append(0).append(Integer.toHexString(b & 0xff));
                } else {
                    sb.append(Integer.toHexString(b & 0xff));
                }
            }

            return sb.toString();
        }

        return null;
    }


}
